package com.arsn.myf.security.service;

import com.arsn.myf.common.util.auth.AuthUtil;
import com.arsn.myf.security.entity.UserInfo;
import com.arsn.myf.system.entity.Role;
import com.arsn.myf.system.entity.User;
import com.arsn.myf.system.service.RoleService;
import com.arsn.myf.system.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 自定义校验
 * @author zhongrj
 * @since 2022-06-16
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //查询用户信息
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("account",username).eq("is_deleted",0).eq("status",1);
        User user = userService.getOne(wrapper);
        // null?
        if (null==user){
            throw  new UsernameNotFoundException("用户名不存在");
        }
        //创建用户信息返回对象
        UserInfo userInfo = userHandle(user);
        //返回数据
        return userInfo;
    }

    /**
     * 用户信息处理
     * @param user 用户对象
     * @return
     */
    private UserInfo userHandle(User user) {
        //用户信息设置
        UserInfo userInfo = new UserInfo();
        userInfo.setId(user.getId());
        userInfo.setUsername(user.getAccount());
        userInfo.setPassword(user.getPassword());
        userInfo.setUser(user);

        // 模拟从数据库中获取用户角色
        List<Role> roleList = userService.getRoleByUserId(user.getId());
        // 处理
        if (roleList.size()>0){
            Set authoritiesSet = new HashSet();
            List<String> list = new ArrayList<>();
            for (Role role : roleList) {
                list.add("role_" + role.getRoleCode());
            }
            GrantedAuthority authority = new SimpleGrantedAuthority(String.join(",", list));
            authoritiesSet.add(authority);
            userInfo.setAuthorities(authoritiesSet);
        }
        //返回
        return userInfo;
    }
}

